import { Paths } from "@/paths";
import { CloseOutlined } from "@ant-design/icons";
import { Typography } from "antd";
import classnames from "classnames";
import React, { DragEventHandler, MouseEventHandler, useEffect, useRef } from "react";
import { IEditorInfo } from "../IEditorInfo";
import styles from "./style.module.scss";

export interface ITabButtonProps extends React.HTMLAttributes<HTMLButtonElement> {
  info: IEditorInfo;
  actived?: boolean;
  on_ref?: (ele: HTMLElement | null) => void;
  on_deleted?(): void;
}
export function TabButton(props: ITabButtonProps) {
  const { children, className, info, onDragStart, onDragEnd, on_deleted, actived = false, on_ref, ..._p } = props
  const root_classname = classnames(
    styles.tab_btn,
    {
      [styles.tab_btn_active]: actived
    },
    className
  )
  const on_drag_start: DragEventHandler<HTMLButtonElement> = (e) => {
    onDragStart?.(e)
  }
  const on_drag_end: DragEventHandler<HTMLButtonElement> = (e) => {
    onDragEnd?.(e)
  }
  const on_click_delete: MouseEventHandler = (e) => {
    e.stopPropagation();
    e.preventDefault()
    on_deleted?.()
  }
  const ref_me = useRef<HTMLButtonElement | null>(null)
  useEffect(() => {
    actived && ref_me.current?.scrollIntoView({ behavior: 'smooth' })
  }, [actived])
  return (
    <button
      draggable
      {..._p}
      ref={r => {
        on_ref?.(r)
        ref_me.current = r;
      }}
      className={root_classname}
      onDragStart={on_drag_start}
      onDragEnd={on_drag_end}
      info-id={info.uid}
      info-kind={info.kind}
      info-title={info.title}>
      {Paths.Icons[info.kind as Paths.All]}
      <Typography.Text >
        {info.title} {children}
      </Typography.Text>
      <Typography.Text className={styles.tab_btn_close} onClick={on_click_delete}>
        <CloseOutlined />
      </Typography.Text>
      <div className={styles.tab_btn_bottom}></div>
    </button >
  )
}
TabButton.ATTR_INFO_ID = 'info-id'